let DateUtil = require('../../utils/dateUtil.js')
import { CouponModel } from '../../models/CouponModel.js'
let Coupon = new CouponModel()
let App = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
 
        coupons:[],
        date:'',
        openId:'',
        active:1,
        coupons:[],
        selectIndex:0,
        subPrice:0,
        couponId:'',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this._init(options)
    },
    _init: async function(options){
        await this._getCoupons()
        await this._getSelectIndex(options)

    },
    _getSelectIndex:function(options){
        let couponId = options.couponId
        let coupons = this.data.coupons
        let that = this
        if(couponId == ''){
            return
        }else{
            coupons.forEach(function(item,index,arr){
                if(item._id == couponId){
                    that.setData({
                        selectIndex:index,
                        subPrice:item.sub_price
                    })
                }
                
            })
        }
    },
 
    //   获取可用优惠券
    _getCoupons: async function(){
        let coupons = await Coupon.getUsefulCoupons()
        console.log(coupons)
        if(coupons.length > 0){
            this.setData({
                coupons:coupons,
                subPrice:coupons[0].sub_price,
                couponId:coupons[0]._id
            })
        }
    },  
   checkCoupon:function(e){
        let index = e.currentTarget.dataset.index
        let couponId = e.detail.couponId
        if(index == this.data.selectIndex){
            this.setData({
                selectIndex:-1,
                subPrice:0
            })
        }else{
            this.setData({
                selectIndex : index,
                subPrice : this.data.coupons[index].sub_price,
                couponId:couponId
            })
        }
        
       
   },
   submit:async function(){
    let couponId = this.data.couponId
    //获取页面栈
    var pages = getCurrentPages();
    var Page = pages[pages.length - 1];//当前页
    if(pages.length > 1){ //说明有上一页存在
        //上一个页面实例对象
        var prePage = pages[pages.length - 2];
        //关键在这里，调用上一页的函数
        if(this.data.selectIndex >= 0){
            prePage.setData({
                couponId:couponId
            })
        }else{
            prePage.setData({
                couponId:''
            })
        }
       
    }
    wx.navigateBack({
      delta: 1,
    })
   },


   
})